{
  "cells": [
    {
      "cell_type": "raw",
      "id": "afaf8039",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: WatsonxToolkit\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e49f1e0d",
      "metadata": {},
      "source": [
        "# WatsonxToolkit\n",
        "\n",
        "This will help you getting started with the [WatsonxToolkit](/docs/concepts/#toolkits). For detailed documentation of all WatsonxToolkit features and configurations head to the [API reference](https://api.js.langchain.com/modules/_langchain_community.agents_toolkits_ibm.html).\n",
        "\n",
        "The toolkit contains following tools:\n",
        "\n",
        "| Name | Description |\n",
        "| ---- | ----------- |\n",
        "| `GoogleSearch` | Search for online trends, news, current events, real-time information, or research topics. |\n",
        "| `WebCrawler` | Useful for when you need to summarize a webpage. Do not use for Web search. |\n",
        "| `SDXLTurbo` | Generate an image from text using Stability.ai |\n",
        "| `Weather` | Find the weather for a city. |\n",
        "| `RAGQuery` | Search the documents in a vector index. |\n",
        "\n",
        "\n",
        "### Integration details\n",
        "\n",
        "| Class | Package | [PY support](https://python.langchain.com/docs/integrations/tools/ibm_watsonx/) | Package latest |\n",
        "| :--- | :--- | :---: | :---: |\n",
        "| [WatsonxToolkit](https://api.js.langchain.com/classes/_langchain_community.agents_toolkits_ibm.WatsonxToolkit.html) | [`@langchain/community`](https://www.npmjs.com/package/@langchain/community) | ✅ | ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |\n",
        "\n",
        "## Setup\n",
        "\n",
        "If you want to get automated tracing from runs of individual tools, you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "`typescript\n",
        "process.env.LANGSMITH_TRACING=\"true\"\n",
        "process.env.LANGSMITH_API_KEY=\"your-api-key\"\n",
        "`\n",
        "\n",
        "### Installation\n",
        "\n",
        "This toolkit lives in the `@langchain/community` package:\n",
        "\n",
        "`{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/community @langchain/core\n",
        "</Npm2Yarn>\n",
        "`"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a38cde65-254d-4219-a441-068766c0d4b5",
      "metadata": {},
      "source": [
        "## Instantiation\n",
        "\n",
        "Now we can instantiate our toolkit:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "cb09c344-1836-4e0c-acf8-11d13ac1dbae",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[Module: null prototype] { default: {} }"
            ]
          },
          "execution_count": 1,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import { WatsonxToolkit } from \"@langchain/community/agents/toolkits/ibm\";\n",
        "import \"dotenv/config\"\n",
        "\n",
        "const toolkit = await WatsonxToolkit.init({\n",
        "   version: '2024-05-31',\n",
        "   serviceUrl: process.env.WATSONX_AI_SERVICE_URL\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5c5f2839-4020-424e-9fc9-07777eede442",
      "metadata": {},
      "source": [
        "## Tools\n",
        "\n",
        "View available tools:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "51a60dbe-9f2e-4e04-bb62-23968f17164a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            " {\n",
            " name: \"GoogleSearch\",\n",
            " description: \"Search for online trends, news, current events, real-time information, or research topics.\"\n",
            " },\n",
            " {\n",
            " name: \"WebCrawler\",\n",
            " description: \"Useful for when you need to summarize a webpage. Do not use for Web search.\"\n",
            " },\n",
            " {\n",
            " name: \"SDXLTurbo\",\n",
            " description: \"Generate an image from text using Stability.ai\"\n",
            " },\n",
            " { name: \"Weather\", description: \"Find the weather for a city.\" },\n",
            " {\n",
            " name: \"RAGQuery\",\n",
            " description: \"Search the documents in a vector index.\"\n",
            " }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const tools = toolkit.getTools();\n",
        "\n",
        "console.log(tools.map((tool) => ({\n",
        "   name: tool.name,\n",
        "   description: tool.description,\n",
        "})))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d11245ad-3661-4405-8558-1188896347ec",
      "metadata": {},
      "source": [
        "For detailed info about tools please visit [watsonx.ai API docs](https://cloud.ibm.com/apidocs/watsonx-ai#get-utility-agent-tools)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dfe8aad4-8626-4330-98a9-7ea1ca5d2e0e",
      "metadata": {},
      "source": [
        "## Use within an agent\n",
        "\n",
        "First, ensure you have LangGraph installed:\n",
        "\n",
        "```{=mdx}\n",
        "<Npm2Yarn>\n",
        " @langchain/langgraph\n",
        "</Npm2Yarn>\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c6d2ca9c",
      "metadata": {},
      "source": [
        "Then, instantiate your LLM to be used in the React agent:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5af22142",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { ChatWatsonx } from \"@langchain/community/chat_models/ibm\";\n",
        "\n",
        "const llm = new ChatWatsonx({\n",
        "   version: '2024-05-31',\n",
        "   serviceUrl: process.env.WATSONX_AI_SERVICE_URL,\n",
        "   model: 'ibm/granite-3-8b-instruct',\n",
        "   projectId: process.env.WATSONX_AI_PROJECT_ID\n",
        "});"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "310bf18e-6c9a-4072-b86e-47bc1fcca29d",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { createReactAgent } from \"@langchain/langgraph/prebuilt\"\n",
        "\n",
        "const agent = createReactAgent({ llm, tools });"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "23e11cc9-abd6-4855-a7eb-799f45ca01ae",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Who won F1 championship in 2022?\n",
            "[\n",
            " {\n",
            " name: \"GoogleSearch\",\n",
            " args: { input: \"F1 championship 2022\" },\n",
            " type: \"tool_call\",\n",
            " id: \"chatcmpl-tool-9da3456b9bbc475fb822296fdb8353a8\"\n",
            " }\n",
            "]\n",
            "[{\"title\":\"2022 DRIVER STANDINGS\",\"description\":\"Official F1® Race Programme · Modern Slavery Statement; Do Not Sell or Share My Personal Information. Formula 1. © 2003-2025 Formula One World Championship ...\",\"url\":\"https://www.formula1.com/en/results/2022/drivers\"},{\"title\":\"2022 Formula One World Championship - Wikipedia\",\"description\":\"2022 Formula One World Championship · Max Verstappen won his second consecutive World Drivers' Championship driving for Red Bull Racing. · Charles Leclerc ...\",\"url\":\"https://en.wikipedia.org/wiki/2022_Formula_One_World_Championship\"},{\"title\":\"2022 Formula One World Championship - Simple English Wikipedia ...\",\"description\":\"Max Verstappen, who was the reigning Drivers' Champion, claimed his second title at the Japanese Grand Prix, while his team, Red Bull Racing, achieved their ...\",\"url\":\"https://simple.wikipedia.org/wiki/2022_Formula_One_World_Championship\"},{\"title\":\"Max Verstappen wins the 2022 F1 Drivers World Championship : r ...\",\"description\":\"Oct 9, 2022 ... One day this guy will win a championship just by finishing the race and celebrating with a world championship lap on the day he won.\",\"url\":\"https://www.reddit.com/r/sports/comments/xzg8pf/max_verstappen_wins_the_2022_f1_drivers_world/\"},{\"title\":\"Red Bull Simulator Championship Edition | F1 Authentics\",\"description\":\"Based on the livery of the 2022 Oracle Red Bull Racing Championship-winning RB18, this F1 simulator has been expertly engineered and manufactured by Memento ...\",\"url\":\"https://www.f1authentics.com/products/red-bull-simulator-championship-edition\"},{\"title\":\"F1 2022 Drivers Championship without Max Verstappen : r/formula1\",\"description\":\"Nov 26, 2022 ... 1.1K votes, 65 comments. 5.2M subscribers in the formula1 community. Welcome to r/Formula1, the best independent online Formula 1 community!\",\"url\":\"https://www.reddit.com/r/formula1/comments/z5cwl7/f1_2022_drivers_championship_without_max/\"},{\"title\":\"F1® Sim Racing World Championship 2022\",\"description\":\"World Championship 2022 Bahrain International Circuit Bahrain International Circuit Race Distance: 29 laps Track Length: 5.412 km\",\"url\":\"https://f1esports.com/world/results/2022\"},{\"title\":\"Our personal F1 2022 Predictions Championship : r/formula1\",\"description\":\"May 5, 2022 ... F1 2025 Driver Predictions from mathematical model. Leclerc and Sainz predicted to beat Hamilton and Albon. r/formula1 - F1 2025 Driver ...\",\"url\":\"https://www.reddit.com/r/formula1/comments/uitbbu/our_personal_f1_2022_predictions_championship/\"},{\"title\":\"Haas F1 Team Esports announces roster for 2022 F1 Esports Series ...\",\"description\":\"Sep 13, 2022 ... Haas F1 Team is ready to commence battle in the 2022 F1 Esports Series Pro Championship featuring an updated line-up for this season.\",\"url\":\"https://www.haasf1team.com/news/haas-f1-team-esports-announces-roster-2022-f1-esports-series-pro-championship\"},{\"title\":\"2022 F1 Deconstructors Championship : r/formula1\",\"description\":\"Nov 22, 2022 ... Congratulations to our 2022 champion Carlos Sainz. Alonso put in a late surge but had to settle for second place. Alfa put in the best effort ...\",\"url\":\"https://www.reddit.com/r/formula1/comments/z1pkkx/2022_f1_deconstructors_championship/\"}]\n",
            "Max Verstappen won the 2022 F1 Championship, driving for Red Bull Racing. He claimed his second title at the Japanese Grand Prix.\n"
          ]
        }
      ],
      "source": [
        "const exampleQuery = \"Who won F1 championship in 2022?\"\n",
        "\n",
        "const events = await agent.stream(\n",
        "   { messages: [{ role: \"user\", content: exampleQuery }]},\n",
        "   { streamMode: \"values\", } \n",
        ")\n",
        "\n",
        "for await (const event of events) {\n",
        "  const lastMsg = event.messages[event.messages.length - 1];\n",
        "   if (lastMsg.tool_calls?.length) {\n",
        "      console.dir(lastMsg.tool_calls, { depth: null });\n",
        "   } else if (lastMsg.content) {\n",
        "      console.log(lastMsg.content);\n",
        "   }\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a5bb5ca-c3ae-4a58-be67-2cd18574b9a3",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all `WatsonxToolkit` features and configurations head to the [API\n",
        " reference](https://api.js.langchain.com/modules/_langchain_community.agents_toolkits_ibm.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0e50eb1c",
      "metadata": {},
      "source": []
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Deno",
      "language": "typescript",
      "name": "deno"
    },
    "language_info": {
      "codemirror_mode": "typescript",
      "file_extension": ".ts",
      "mimetype": "text/x.typescript",
      "name": "typescript",
      "nbconvert_exporter": "script",
      "pygments_lexer": "typescript",
      "version": "5.6.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
